// Base64 编码表
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

/**
 * Base64 编码：支持 UTF-8 字符集
 * @param {string} input 要编码的字符串
 * @returns {string} Base64 编码结果
 */
export function base64Encode(input = '') {
  // 将 Unicode 字符串转换为 UTF-8 编码
  const utf8Str = unescape(encodeURIComponent(input));
  let output = '';

  for (
    let block = 0, charCode, idx = 0, map = chars;
    utf8Str.charAt(idx | 0) || (map = '=', idx % 1);
    output += map.charAt(63 & (block >> (8 - (idx % 1) * 8)))
  ) {
    charCode = utf8Str.charCodeAt((idx += 3 / 4));
    block = (block << 8) | charCode;
  }
  
  return output;
}

/**
 * Base64 解码：支持 UTF-8 字符集
 * @param {string} input Base64 字符串
 * @returns {string} 解码 UTF-8 字符串
 */
export function base64Decode(input = '') {
  // 去除 Base64 合法字符串中的填充符 '='
  const str = input.replace(/=+$/, '');
  let output = '';

  if (str.length % 4 === 1) {
    throw new Error("'base64Decode' failed: The string to be decoded is not correctly encoded.");
  }

  for (
    let bc = 0, bs, buffer, idx = 0;
    (buffer = str.charAt(idx++));
    ~buffer && ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4)
      ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))
      : 0
  ) {
    buffer = chars.indexOf(buffer);
  }

  // 将 UTF-8 编码恢复为 Unicode 字符串
  try {
    return decodeURIComponent(escape(output));
  } catch (e) {
    console.error(`Base64 解码错误: ${input}`, e);
    throw e;
  }
}
